<template>
	<view class="content">
		<view class="body">
			<!-- 头部logo -->
			<view class="header">
				<image :src="logoImage"></image>
			</view>
			<!-- #ifndef MP-WEIXIN -->

			<!-- 主体表单 -->
			<view class="main">
				<wInput v-model="phoneData" type="text" maxlength="11" placeholder="用户名/电话"></wInput>
				<wInput v-model="passData" type="password" maxlength="11" placeholder="密码"></wInput>
			</view>
			<wButton text="登 录" :rotate="isRotate" @click.native="startLogin()"></wButton>
			<!-- #endif -->


			<!-- 其他登录 -->
			<!-- #ifdef MP-WEIXIN -->
			<!-- <view @click="authUserInfo" v-if="!isBindPhone">
				<view class="quick_login">
					<view class="t"><text class="title-wrap">微信授权登录</text></view>
				</view>
				<view  class="quick_login_list">
					<text class="wechat"></text>
				</view>
				
			</view>
			<view class="get-phone" v-else>
				<button type="default" open-type="getPhoneNumber" @getphonenumber="getminiprogramcode">微信手机号一键授权</button>
			</view> -->
			<view class="get-user" v-if="!isAuthUser">
				<button type="primary" class="auth-btn btn" @click="authUserInfo">微信授权登录</button>
				<button type="default" :plain="true" class="cancel-btn btn" @click="cancelAuthUser">取消</button>
				
			</view>
			
			<view  v-else>
				<view class="get-phone">
					<button type="default" :plain="true" class="cancel-btn btn" @click="cancelAuthUser">取消</button>
					<button type="primary" class="phone-btn btn" open-type="getPhoneNumber"
						@getphonenumber="getminiprogramcode">微信登录</button>
				</view>
			</view>
			<!-- #endif -->

			<!-- #ifndef MP-WEIXIN -->
			<!-- 底部信息 -->
			<view class="footer">
				<navigator url="forget" open-type="navigate">找回密码</navigator>
				<text class="line">|</text>
				<navigator url="reg" open-type="navigate">注册账号</navigator>
			</view>
			<!-- #endif -->

		</view>
	</view>
</template>

<script>
	var _this;
	import wInput from '../../components/watch-login/watch-input.vue' //input
	import wButton from '../../components/watch-login/watch-button.vue' //button
	import {
		mpWechatLogin,
		authLogin,
	} from '@/api/login';

	import {
		mapMutations
	} from 'vuex';
	export default {
		data() {
			return {
				logoImage: '/static/logo.jpg',
				phoneData: '', //用户/电话
				passData: '', //密码
				isRotate: false, //是否加载旋转
				btnLoading: false,//是否授权
				authCode: '',//授权码
				isBindPhone: false,//是否绑定手机
				
				isAuthUser: '', //是否授权过用户信息
				miniappcode: '',//uni.login获取的授权code
			};
		},
		components: {
			wInput,
			wButton,
		},
		
		onLoad(option) {
			_this = this;
			this.isAuthUser = this.$mStore.state.authUserInfo || '';
			console.log('是否授权过',this.isAuthUser)
			if(this.isAuthUser){
				this.authUserCache = this.$mStore.state.authUserInfo || '';
			}else{
				_this.$mStore.commit('removeAuthUser');
			}
			/* if(option && option.bind_phone){
				//绑定手机操作
				this.isBindPhone = true;
				
			}else{
				this.isBindPhone = false;
			} */
			this.initLogin();
			
			
		},
		onShow() {
			
			
		
		},
		mounted() {
			
			//this.isLogin();
		},
		methods: {
			...mapMutations(['login']),
			
			async startLogin(){
				console.log(111)
				//登录
				if(this.isRotate){
					//判断是否加载中，避免重复点击请求
					return false;
				}
				if (this.phoneData.length == "") {
				     uni.showToast({
				        icon: 'none',
						position: 'bottom',
				        title: '用户名不能为空'
				    });
				    return;
				}
			    if (this.passData.length < 5) {
			        uni.showToast({
			            icon: 'none',
						position: 'bottom',
			            title: '密码格式不正确'
			        });
			        return;
			    }
				const result = await this.$api.json('userInfo');
				if(result.status === 1){
					this.login(result.data);
				    uni.navigateBack();  
				}else{
					this.$api.msg(result.msg);
					this.logining = false;
				}
				/* this.isRotate=true
				this.$api.webLogin(this.phoneData, this.passData).then((res)=>{
					this.isRotate=false;
					//获取用户信息
					this.$api.getUser(this.phoneData, res.body).then(user=>{
						this.isRotate=false;
						this.login(user);
						uni.navigateBack();  
					}).catch((message)=>{
						uni.showToast({
						    icon: 'none',
							position: 'bottom',
						    title: message
						});
					});
				}).catch((message)=>{
					this.isRotate=false;
					uni.showToast({
					    icon: 'none',
						position: 'bottom',
					    title: message
					});
				}); */
			},
			initLogin(){
				_this.$mStore.commit('removeMiniappcode');
				
				// session_key 已经失效，重新登录
				uni.login({
					provider: 'weixin',
					scopes: 'auth_user',
					success: function(loginRes) {
						_this.$mStore.commit('updateMiniappcode',loginRes.code);
						console.log('登录成功', loginRes,_this.$mStore.state.miniappcode,_this.$mStore.state.isAuthUser);
						
					},
					fail: function() {
						
						_this.$mHelper.toast('微信登录授权失败!');
						
					}
				});
				
			},
			
			/**
			 * 取消授权
			 */
			cancelAuthUser(){
				console.log('取消授权');
				// 判断是否有上一页
				let pages = getCurrentPages(),
					prePage = pages[pages.length - 2];
				console.log('当前页面',prePage)
				if(!prePage){
					uni.reLaunch({
						url:'/pages/user/user'
					})
					return false;
				}
				uni.navigateBack({
					delta:1
				})
				// this.$mRouter.back();
				
			},
			cancelAuthPhone(){
				console.log('取消授权手机')
				uni.showModal({
					title:'温馨提示',
					content:'若您没有授权，可以使用手机号进行登录',
					confirmText:'前往登录',
					cancelText:'暂不',
					success(res) {
						if(res.confirm){
							uni.navigateTo({
								url:'/pages/user/login'
							})
						}
						
					}
				})
				
			},
			
			removeSessionKey(code){
				uni.removeStorageSync('session_key');
				
			},
			saveSessionKey(code){
				uni.setStorageSync('session_key',code)
				
			},
			getSessionKey(){
				return uni.getStorageSync('session_key')
			},
			
			//小程序授权登录接口
			/* getminiprogramcode111(e) {
				console.log(e)
				var _this = this;
				//检验session_key是否过期，过期就要重新调用wx.login获取session_key 
				uni.checkSession({
					success(res) {
						console.log('session_key 未过期',res,e)
						//session_key 未过期，并且在本生命周期一直有效
					
						_this.getPhoneNumber(e);
					},
					fail(res) {
						console.log('session_key 已经失效',res);
						
						
						uni.login({
							provider: 'weixin',
							scopes: 'auth_user',
							success: function(loginRes) {
								
								_this.getPhoneNumber(e);
						
							},
							fail: function() {
								
								_this.$mHelper.toast('微信登录授权失败!');
								
							}
						});
					}
				});
			}, */
			//小程序授权登录接口
			getminiprogramcode(e) {
				console.log(e)
				var _this = this;
				_this.getPhoneNumber(e);
				/* //检验session_key是否过期，过期就要重新调用wx.login获取session_key 
				uni.checkSession({
					success(res) {
						console.log('session_key 未过期',res,e,_this.$mStore.state.miniappcode);
						console.log('授权code',_this.$mStore.state.miniappcode,uni.getStorageSync('lzj_miniappcode'))
						//session_key 未过期，并且在本生命周期一直有效
						_this.getPhoneNumber(e);
					},
					fail(res) {
						_this.$mStore.commit('removeMiniappcode');
						console.log('session_key 已经失效',res);
						
						// session_key 已经失效，重新登录
						uni.login({
							provider: 'weixin',
							scopes: 'auth_user',
							success: function(loginRes) {
								_this.$mStore.commit('updateMiniappcode',loginRes.code);
								console.log('登录成功', loginRes,_this.$mStore.state.miniappcode);
								
								_this.getPhoneNumber(e);
							},
							fail: function() {
								
								_this.$mHelper.toast('微信登录授权失败!');
								
							}
						});
					}
				}); */
			},
			async getPhoneNumber(e) {
				var _this = this;
				console.log('授权后的处理',e.detail.errMsg,e);
				//授权后的处理
				if (e.detail.errMsg == 'getPhoneNumber:ok') {
					//点击获取的信息
					let params = {
						encrypted_data: e.detail.encryptedData,
						iv: e.detail.iv,
						code : _this.$mStore.state.miniappcode,
						userInfo: JSON.stringify(_this.authUserCache),
					};
					console.log('登录传参',params)
					// return ;
					await _this.$http.post(`${mpWechatLogin}`,params,{header: {'Content-Type':'application/json'}}).then(res=>{
						if(res.code === _this.sucCode){
							//手机号授权绑定成功
							/* _this.$mHelper.toast(res.msg);
							let userInfo = _this.$mStore.state.userInfo;
							if(userInfo && res.data && res.data.know_phone){
								userInfo.know_phone = res.data.know_phone
								//更新用户信息缓存
								_this.$mStore.commit('updateUserInfo',userInfo)
							} */
							let rData = res.data;  
							_this.$mHelper.toast(res.msg);  
							// 保存到缓存
							 _this.$mStore.commit('login', rData);
							
							//清除多余缓存
							_this.$mStore.commit('removeMiniappcode');
							_this.$mStore.state.isAuthUser = false,
							
							setTimeout(function(){
								_this.jump();
								
							},1000);
						}else{
							_this.$mHelper.toast(res.msg);
						}
						
					}).catch(err=>{
						console.log('手机号授权绑定失败',err);
					})
					
				}else{
					// this.cancelAuthPhone();
				}
			},
			
			

			authUserInfo(){
				// #ifdef MP-WEIXIN
				uni.getSetting({
				 success(res) {
					console.log("授权：",res);
				   if (!res.authSetting['scope.userInfo']) {
						//这里调用授权
						console.log("当前未授权");
						uni.openSetting({
						  success(res) {
						    console.log(res.authSetting)
						  }
						});
				   } else {
						//用户已经授权过了
						_this.toAuthLogin1();
						console.log("当前已授权");
				   }
				 }
			   })
			   //#endif
				
			},

			
			toAuthLogin1() {
				if (!uni.getUserProfile) {
					this.toAuthLoginOld();
					return false;
				}
				console.log("aaaa")
				let authApi = '';
				this.btnLoading = true;
				uni.showLoading();
				uni.getUserProfile({
					desc: '登录', // 这个参数是必须的  
					success: (infoRes) => {
						console.log(1111, infoRes);
						if (infoRes) {
							_this.authUserCache = infoRes.userInfo || '';
							_this.isAuthUser = 1;
							_this.$mStore.state.isAuthUser = 1;
							_this.$mStore.commit('updateAuthUser', _this.authUserCache);
							_this.$forceUpdate();
							console.log(22, _this.$mStore.state.authUserInfo)
						}
			
						uni.hideLoading();
					},
					fail: err => {
						this.btnLoading = false;
						console.log(err);
						uni.hideLoading();
					}
				})
			
			},
			// 授权登录
			toAuthLogin() {
				this.btnLoading = true;

				let authApi;
				// #ifdef MP-WEIXIN
				uni.getProvider({
					service: 'oauth',
					success: function(res) {
						if (~res.provider.indexOf('weixin')) {
							uni.login({
								provider: 'weixin',
								success: function(loginRes) {
									console.log("新版获取用户信息111", loginRes);


									uni.getUserInfo({
										provider: 'weixin',
										success: function(infoRes) {
											console.log("老版获取用户信息", infoRes);
											if (infoRes) {
												_this.authUserCache = infoRes.userInfo || '';
												_this.isAuthUser = 1;
												_this.$mStore.state.isAuthUser = 1;
												_this.$mStore.commit('updateAuthUser', _this.authUserCache);
												_this.$forceUpdate();
												// console.log(22, _this.authUserCache)
											}

											/* let params = {};
											authApi = mpWechatLogin;

											params.raw_data = infoRes.rawData;
											params.encrypted_data = infoRes
												.encryptedData;
											params.iv = infoRes.iv;
											params.signature = infoRes.signature;

											params.code = loginRes.code;
											console.log('微信授权返回结果', params);
											_this.thirdPartyAuthLogin(authApi, params); */
										},
										fail: err => {
											_this.$mHelper.toast('微信授权失败');
											console.log('授权失败', err)
											_this.btnLoading = false;
										}
									});
								},
								fail: function() {
									_this.$mHelper.toast('微信登录授权失败!');
									_this.btnLoading = false;
									_this.$mHelper.log('暂不支持小程序登录');
								}
							});
						} else {
							uni.showToast({
								title: '请先安装微信或升级版本',
								icon: 'none'
							});
						}
					}
				});
				// #endif
			},
			/**
			 * 第三方授权登录处理
			 */
			async thirdPartyAuthLogin(authApi, params = {}) {
				if (_this.parent_id) {
					params.parent_id = _this.parent_id;
				}

				_this.$http
					.post(authApi, params)
					.then(async r => {
						console.log('微信登录！', r);
						_this.btnLoading = false;
						uni.hideLoading();
						if (r.code === _this.sucCode) {
							console.log('微信登录2222！', r);
							let rData = r.data,
								userInfo = rData;
							_this.$mHelper.toast(r.msg);
							// 保存到缓存
							await _this.$mStore.commit('login', userInfo);
								
							// _this.jump();
							if(!rData.know_phone){
								//未绑定手机号绑定手机号
								uni.showModal({
									title:'温馨提示',
									content:'您还未绑定手机号，请授权手机号绑定',
									cancelText:'暂不',
									success(result) {
										if(result.confirm){
											_this.isBindPhone = true;
											
										}else{
											_this.jump();
										}
									}
								})
							}else{
								_this.jump();
							}


						} else {
							//授权失败
							_this.$mHelper.toast(r.msg);
						}





					})
					.catch((err) => {
						console.log('请求错误111', err);
						uni.hideLoading();
					});

			},
			/**
			 * 跳转选择
			 */
			async jump() {
				let backToPage = _this.$mHelper.getBackPage();
				// console.log('上一个页面存在',uni.getStorageInfoSync('backToPage'));
				if (backToPage) {
					backToPage = JSON.parse(backToPage)
					let backUrl = backToPage.route || '';
					// console.log('上一个页面存在', backToPage, backToPage.route, backUrl);
					if (_this.$mHelper.checkTabBarUrl(backUrl)) {
						_this.$mRouter.reLaunch(backToPage);
					} else {
			
						_this.$mRouter.redirectTo(backToPage);
					}
					await _this.$mHelper.removeBackPageStorage();
			
				} else {
					console.log('上一个页面不存在，直接跳转首页', backToPage);
					// 跳转首页
					_this.$mRouter.reLaunch({
						route: _this.$mRoutesConfig.main.path
					});
				}
			
			},
			/**
			 * 暂不登录，跳转首页
			 */
			noLogin() {
				/* let url = this.$mRoutesConfig.main.path;
				this.$mRouter.reLaunch({
					route: url
				}); */
				this.jump();
			}
		}
	}
</script>

<style>
	page {
		overflow: hidden;
	}

	/* 头部 logo */
	.header {
		width: 161upx;
		height: 161upx;
		box-shadow: 0upx 0upx 60upx 0upx rgba(0, 0, 0, 0.1);
		border-radius: 50%;
		margin-top: 80upx;
		margin-bottom: 50upx;
		margin-left: auto;
		margin-right: auto;
	}

	.header image {
		width: 161upx;
		height: 161upx;
		border-radius: 50%;
	}

	/* 主体 */
	.main {
		display: flex;
		flex-direction: column;
		padding-left: 70upx;
		padding-right: 70upx;
	}

	.tips {
		color: #999999;
		font-size: 28upx;
		margin-top: 64upx;
		margin-left: 48upx;
	}

	/* 其他登录方式 */
	.other_login {
		display: flex;
		flex-direction: row;
		justify-content: center;
		align-items: center;
		margin-top: 256upx;
		text-align: center;
	}

	.login_icon {
		border: none;
		font-size: 64upx;
		margin: 0 64upx 0 64upx;
		color: rgba(0, 0, 0, 0.7)
	}

	.wechat_color {
		color: #83DC42;
	}

	.weibo_color {
		color: #F9221D;
	}

	.github_color {
		color: #24292E;
	}

	/* 底部 */
	.footer {
		display: flex;
		flex-direction: row;
		justify-content: center;
		align-items: center;
		font-size: 28upx;
		margin-top: 64upx;
		color: rgba(0, 0, 0, 0.7);
		text-align: center;
		height: 40upx;
		line-height: 40upx;
	}

	.footer .t {
		margin-top: 3upx;
	}

	.footer .line {
		font-size: 24upx;
		margin-left: 15upx;
		margin-right: 15upx;
	}

	.quick_login {
		padding: 40upx 100upx 40upx;
		flex: 1;
		background: #fff;
		margin-top: 0upx;
		display: flex;
	}

	.quick_login .t {
		height: 24upx;
		border-bottom: 0px solid #ddd;
		text-align: center;
		width: 100%;
		margin: 0 auto;
	}

	.quick_login .title-wrap {
		display: inline-block;
		height: 32upx;
		padding: 0 20upx;
		color: #000;
		line-height: 32upx;
		font-size: 32upx;
		font-weight: normal;
		background: #fff;
	}

	.quick_login_list {
		text-align: center;
		margin-top: 20upx;
		background: #fff;
		border: none
	}

	uni-button:after,
	button:after {
		display: none;
	}

	.quick_login_list .wechat {
		display: inline-block;
		width: 120upx;
		height: 120upx;
		border: #2dbb5f solid 1px;
		border-radius: 50%;
		position: relative;
	}

	.quick_login_list .wechat:after {
		font-family: iconfont;
		font-size: inherit;
		line-height: 1;
		position: absolute;
		top: 50%;
		display: inline-block;
		-webkit-transform: translateY(-50%);
		transform: translateY(-50%);
		text-decoration: none;
		color: #2dbb5f;
		-webkit-font-smoothing: antialiased;
		right: 15px;
		font-size: 60upx;
		content: '\e604';
	}
	
	
</style>
<style lang="scss">
	.body{
		padding: 0 40rpx;
	}
	.btn {
		height: 90rpx;
		line-height: 90rpx;
		font-size: 30rpx;
		border-radius: 50rpx;
	}
	
	.cancel-btn {
		color: #999999 !important;
		font-weight: bold;
	}
	
	.get-user {
		margin-top: 200rpx;
		.auth-btn {
	
			margin-bottom: 30rpx;
		}
	
		.phone-btn {
			border-radius: 50rpx;
		}
	
	}
	
	.get-phone {
		margin-top: 300rpx;
		display: flex;
		align-items: center;
		justify-content: space-between;
		.btn{
			width:45%;
			// flex: 1 1 auto;
		}
	}
	
	.phone-login{
		display: flex;
		flex-direction: column;
		align-items: center;
		margin-top: 150rpx;
		.phone-title{
			margin-bottom: 20rpx;
			font-size: 30rpx;
			color: #999999;
		}
		.phone-logo{
			width: 64rpx;
			height: 64rpx;
		}
		
	}
</style>
